$(function () {
    var userInfo = LoginStatus();
    //数据渲染

    //求职状态
    SelectLoad('/user/prop/jobHuntingStatus/list?page=0&limit=2000&name=','get','jobHuntingStatus','name');
    //期望职位
    var formSelects = layui.formSelects;
    // btns(formSelects,'expectPosition')
    // var PositionArray = arrayAjax('/user/prop/position/list?page=0&limit=2000','get')
    // formSelect(formSelects,'expectPosition','get','/user/prop/position/list?page=0&limit=2000','positionName',true,"/user/prop/position",PositionArray);
    // tip(formSelects,'expectPosition')

    
    layui.use(['treeSelect','form'], function () {
        var treeSelect= layui.treeSelect;
        treeSelect.render({
            // 选择器
            elem: '#expectPosition',
            // 数据
            data: "../js/data/data.json",
            // 异步加载方式：get/post，默认get
            type: 'get',
            // 占位符
            placeholder: '请选择职位',
            // 是否开启搜索功能：true/false，默认false
            search: false,
            // 点击回调
            click: function(d){
                $("input[name='expectPosition']").val(d.current.value)
                // console.log()
            },
            // 加载完成后的回调函数
            success: function (d) {
                // 选中节点，根据id筛选
                if($.cookie("careerObjectives")){
                    var careerObjectives = $.cookie("careerObjectives");
                    var obj = JSON.parse(careerObjectives)
                    treeSelect.checkNode('expectPosition', obj[0].expectPosition);
                    $("input[name='expectPosition']").val(obj[0].expectPosition)
                }
            }
        });
    });
    //城市
    layui.use(['treeSelect','form'], function () {
        var treeSelect= layui.treeSelect;

        treeSelect.render({
            // 选择器
            elem: '#expectCity',
            // 数据
            data: companyServices+"/prop/city/tree",
            // 异步加载方式：get/post，默认get
            type: 'get',
            // 占位符
            placeholder: '请选择城市',
            // 是否开启搜索功能：true/false，默认false
            search: false,
            // 点击回调
            click: function(d){
                $("input[name='expectCity']").val(d.current.value)
            },
            // 加载完成后的回调函数
            success: function (d) {
                // 选中节点，根据id筛选
                if($.cookie("careerObjectives")){
                    var careerObjectives = $.cookie("careerObjectives");
                    var obj = JSON.parse(careerObjectives)
                    treeSelect.checkNode('tree', obj[0].expectCity);
                    $("input[name='expectCity']").val(obj[0].expectCity)
                }
            }
        });
    });






    //期望行业
    btns(formSelects,'expectIndustry')
    var IndustryArray = arrayAjax('/user/prop/industry/list?page=0&limit=2000','get')
    formSelect(formSelects,'expectIndustry','get','/user/prop/industry/list?page=0&limit=2000','industryName',true,'/user/prop/industry',IndustryArray);
    tip(formSelects,'expectIndustry')
    //监听
    formSelects.on('expectIndustry', function(id, vals, val, isAdd, isDisabled){
        if(vals.length==3)
            $("#expectIndustry").click();    
    }, true);

    //薪酬
    SelectLoad('/user/prop/salaryLevel/list?page=0&limit=20&name=','get','expectSalaryLevel','name')


    //判断是否存在cookie
    if($.cookie("careerObjectives")){
        var careerObjectives = $.cookie("careerObjectives");
        var obj = JSON.parse(careerObjectives)
    }

    
    //提交
    $("#Submitbtn").click(function(){
        var careerObjectives = [];
        var jobHuntingStatus = $("select[name='jobHuntingStatus']").val();
        if(jobHuntingStatus==null||jobHuntingStatus==""){
            layerMsg("求职状态不为空");
            return false;
        }
        // var expectPosition = formSelects.value('expectPosition', 'valStr'); 
        // var expectPosition = $("select[name='expectPosition']").val();
        var expectPosition=$("input[name='expectPosition']").val()
        if(expectPosition==null||expectPosition==""){
            layerMsg("期望职位不为空");
            return false;
        }

        var expectIndustry = formSelects.value('expectIndustry', 'valStr');
        if(expectIndustry==null||expectIndustry==""){
            layerMsg("期望行业不为空");
            return false;
        }
        var expectIndustry = formSelects.value('expectIndustry', 'valStr');
        var expectCity=$("input[name='expectCity']").val()
        if(expectCity==null||expectCity==""){
            layerMsg("期望城市不为空");
            return false;
        }
        var expectSalaryLevel=$("select[name='expectSalaryLevel']").val()
        if(expectSalaryLevel==null||expectSalaryLevel==""){
            layerMsg("期望薪酬不为空");
            return false;
        }
        var jsondata = {
            "jobHuntingStatus":jobHuntingStatus,
            'expectPosition':expectPosition,
            'expectIndustry':expectIndustry,
            "expectCity":expectCity,
            "expectSalaryLevel":expectSalaryLevel
        }
        careerObjectives.push(jsondata)
        $.cookie('careerObjectives',JSON.stringify(careerObjectives));
        layerMsg("添加成功")
        setTimeout(function() {
            window.location.href="register-advantage.html" ;
        },3000);
    })
    
})


//下拉列表ajax
function SelectLoad(_url,_type,_id,_name){
    _url = services+_url;
    $.ajax({
        type: _type, // 提交方式 get/post
        url:_url,
        async:false,
        // contentType:"application/json;charset=utf-8",
        //解决跨域
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        success: function(res) {
            var obj = JSON.parse(res);
            if(obj.code==0){
                data = obj.data;
                var selectID = "";
                var html = "";
                if($.cookie("careerObjectives")){
                    var careerObjectives = $.cookie("careerObjectives");
                    var obj = JSON.parse(careerObjectives)
                    selectID = obj[0][_id]
                }
                $.each(data, function (index, item) {
                    if (selectID != null && selectID != '' && selectID == item.id) {
                        
                        html += '<option value="'+item.id+'" selected>'+item[_name]+'</option>';
                    } else {
                        html += '<option value="'+item.id+'">'+item[_name]+'</option>';
                    }
                })
                $("#"+_id).append(html);
                // for(var i=0;i<data.length;i++){
                //     $("#"+_id).append("<option value='"+data[i].id+"'>"+data[i][_name]+"</option>");
                // }
                useLayUI()
            }else{
                layerMsg("加载失败，请重试")
            }
        }
    })
}

function formSelect(formSelects,_id,_type,_url,_name,Insert=true,Inserturl="",array=[]){
    formSelects.config(_id, {
        type: _type,                //请求方式: post, get, put, delete...
        searchName: _name,      //自定义搜索内容的key值
        searchVal: '',              //自定义搜索内容, 搜素一次后失效, 优先级高于搜索框中的值
        keyName: _name,            //自定义返回数据中name的key, 默认 name         
        searchUrl: services+_url,
        keyVal: 'id',            //自定义返回数据中value的key, 默认 value
        delay: 500,  //搜索延迟时间, 默认停止输入500ms后开始搜索\
        response: {
            statusCode: 0,          //成功状态码
            statusName: 'code',     //code key
            msgName: 'msg',         //msg key
            dataName: 'data'  ,      //data key
        },            
        beforeSuccess: function(id, url, searchVal,result){  
            
            if(result.code==0){
                if(result.count==0){
                    result.code = 201;
                    result.msg = "没有找到选项";
                    if(Insert){
                        btns(formSelects,id,_url,array,searchVal,Inserturl,'put',_name);
                    }
                }
            }
            return result;  //必须return一个结果, 这个结果要符合对应的数据结构
        },  
     error: function(id, url, searchVal, err){           //使用远程方式的error回调
            //同上
            console.log(err);   //err对象
        },
    success:function () {
        if($.cookie("careerObjectives")){
            var careerObjectives = $.cookie("careerObjectives");
            var obj = JSON.parse(careerObjectives)
            // if(_id=="expectPosition")
                formSelects.value(_id, obj[0][_id].split(','),true);
        }
    }
    }, false)
}

function InsertApi(_addurl,_addtype,_name,_value){
    var arrdata = {};
    arrdata[_name] = _value;
    arrdata["pid"] = '0';
    var result = ""
    $.ajax({
        type: _addtype, // 提交方式 get/post
        url:services+_addurl,
        contentType:"application/json;charset=utf-8",
        async:false,
        // contentType:"application/json;charset=utf-8",
        //解决跨域
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        data:JSON.stringify(arrdata),
         success: function(res) {
            result = JSON.stringify(res);
            ApiLoginStatus(result)
            if(res.success){
                result = res;
            }       
        },
    });
    return result;

}

function localAPi(formSelects,_id,searchVal,key,value,timestamp,array){
    
    var arr = {};
    arr[key]=timestamp;
    arr[value]=searchVal;
    array.push(arr)
    //local模式
    formSelects.data(_id, 'local', {
       arr:array
    });
    return array;
}

function serviceAPI(formSelects,_id,_url){
    formSelects.data(_id, 'server', {
        url:services+_url
    });
}

function btns(formSelects,_id,_url,array,_value="",_addurl="",_addtype="",_name=""){
    formSelects.btns(_id, ['remove', {
        icon: 'layui-icon layui-icon-ok',   //自定义图标, 可以使用layui内置图标
        name: '添加',
        click: function(id){
            if(_value){
                 var res = InsertApi(_addurl,_addtype,_name,_value)
                if(res.success){
                    idvalue = res.data.id;
                    localAPi(formSelects,_id,_value,'id',_name,idvalue,array)
                }
            }
        }
    }]);

}
function search(formSelects,_id,keyword){
    //使用js主动触发搜索
    formSelects.search(_id, keyword);
}

function arrayAjax(_url,_type){
    var array = [];
    $.ajax({
        type: _type, // 提交方式 get/post
        url:services+_url,
        async:false,
        // contentType:"application/json;charset=utf-8",
        //解决跨域
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        success: function(res) {
        var obj = JSON.parse(res)
            if(obj.code==0){
                array = obj.data;
            }
        }
    })
    return array;
}

//提示
function tip(formSelects,selectID){
    formSelects.maxTips(selectID, function(id, vals, val, max){
        //id:   点击select的id
        //vals: 当前select已选中的值
        //val:  当前select点击的值
        //max:  当天多选最大值
        layerMsg("最多只能选择"+max+"个选项")
    });
}

